package com.sakura.system.controller.upload.voide;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 批量上传文件夹中的视频
 */

@Slf4j
//@Controller
@RestController
//@CrossOrigin(origins = "http://127.0.0.1:8080") // 允许特定域进行跨域请求
@RequestMapping("/upload/files/folder/video")
public class FileFolderVideoController {

    @Value("${file.upload-folderv}")
    private String uploadBaseDir;

    @Autowired
    private HttpServletRequest request;

    /**
     * 批量上传视频
     *
     * @param folderPath 文件夹路径
     * @return 上传成功的视频访问地址列表
     *
     * 发送一个POST请求到 /uploadFolder 接口。
     * 在请求参数中，将 folderPath 参数设置为要上传的文件夹路径。
     * 服务器将读取指定路径下的所有文件，并筛选出视频文件进行处理。
     * 对于筛选出的每个视频文件，将其复制到目标文件夹（在这里是 uploadBaseDir 配置的路径）。
     * 构建上传成功的视频访问地址，存储到 uploadedVideoUrls 列表中。
     * 返回 uploadedVideoUrls 列表作为响应结果，其中包含上传成功的视频访问地址列表
     */
    @PostMapping("/uploadFolderssss")
    public List<String> uploadFolder(@RequestParam("folderPath") String folderPath) {
        List<String> uploadedVideoUrls = new ArrayList<>();

        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            return uploadedVideoUrls;
        }

        File uploadDir = new File(uploadBaseDir, folder.getName());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String domain;
        if (request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1")) {
            domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        } else {
            domain = request.getScheme() + "://" + request.getServerName();
        }

        File[] files = folder.listFiles();
        log.info("kais保存!");
        for (File file : files) {
            if (file.isFile()) {
                String originalFilename = file.getName();
                String extension = getFileExtension(originalFilename);

                // 检查文件后缀是否为视频类型
                if (!isVideoFile(extension)) {
                    continue;
                }

                try {
                    String filename = originalFilename;
                    File destFile = new File(uploadDir, filename);

                    // 将文件复制到目标文件夹
                    FileUtils.copyFile(file, destFile);

                    String fileUrl = domain + "/" + uploadDir.getName() + "/" + filename;
                    uploadedVideoUrls.add(fileUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return uploadedVideoUrls;
    }

    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf(".");
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1).toLowerCase();
        }
        return "";
    }

    private boolean isVideoFile(String extension) {
        String[] allowedVideoTypes = {"mp4", "avi", "mov","ts"};
//        新版本
//        return List.of(allowedVideoTypes).contains(extension.toLowerCase());
        for (String type : allowedVideoTypes) {
            if (type.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }


    @PostMapping("/uploadFolder")
    public List<String> uploadFolder(@RequestParam("files") MultipartFile[] files) {
        List<String> uploadedVideoUrls = new ArrayList<>();

        File folder = new File(Arrays.toString(files));
        if (!folder.exists() || !folder.isDirectory()) {
            return uploadedVideoUrls;
        }

        File uploadDir = new File(uploadBaseDir, folder.getName());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String domain;
        if (request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1")) {
            domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        } else {
            domain = request.getScheme() + "://" + request.getServerName();
        }

        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);

            // 检查文件后缀是否为视频类型
            if (!isVideoFile(extension)) {
                continue;
            }

            try {
                String filename = originalFilename;
                File destFile = new File(uploadBaseDir, filename);

                // 将文件保存到目标文件夹
                file.transferTo(destFile);

                String fileUrl = domain + "/" + uploadDir.getName() + "/" + filename;
                uploadedVideoUrls.add(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return uploadedVideoUrls;
    }



}
